<!-- 房屋管理 -->
<template>
  <div>
    <div class="header">
      <div class="title">
        <div style="margin-bottom: 15px; margin-top: 15px">
          <a-space style="margin-left: 13px">
            <span>行政区划：</span>
            <a-input-group compact>
              <a-cascader
                v-model:value="value18"
                style="width: 100%"
                :options="options1"
                expand-trigger="hover"
                placeholder="请选择行政区"
                changeOnSelect
                @change="onChange"
              />
            </a-input-group>
          </a-space>
          <a-space style="margin-left: 10px">
            <span>开始时间：</span>
            <a-date-picker v-model:value="startDate" :format="dateFormat" />
          </a-space>
          <a-space style="margin-left: 10px">
            <span>结束时间：</span>
            <a-date-picker v-model:value="endDate" :format="dateFormat" />
          </a-space>
          <a-space style="width: 8%; margin-top: 15px; margin-left: 25px">
            <a-select ref="select" v-model:value="role_type" style="width: 120px">
    >
              <a-select-option value="4">乡镇用户</a-select-option>
      <a-select-option value="3">区级用户</a-select-option>
              <a-select-option value="2">市级用户</a-select-option>
    </a-select>
          </a-space>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <a-space class="search-btn">
            <a-button type="primary" @click="searchBtn">查询</a-button>
          </a-space>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <space style="float: right; margin-right: 10px">
            <a-button type="primary" @click="handleExport"> 导出统计表</a-button>
          </space>
          <space style="float: right; margin-right: 10px">
            <a-button type="primary" @click="handleMxExport"> 导出核验明细</a-button>
          </space>
        </div>
      </div>
      <a-table
        :dataSource="tableData"
        :columns="displayColumns"
        :pagination="false"
        :scroll="{ x: 1500, y: tableHeight }"
        bordered
        :loading="loading"
      >
        <!-- vue3 中的写法 -->
        <template #headerCell="{ column }">
          <template v-if="column.key == 'xzq'">
            <Tooltip placement="top">
              <template #title>
                <span>区县名称</span>
              </template>
              <span>区县名称 </span>
            </Tooltip>
          </template>

          <template v-if="column.key == 'zcount'">
            <Tooltip placement="top">
              <template #title>
                <span>房屋总数（栋）</span>
              </template>
              <span> 房屋总数（栋） </span>
            </Tooltip>
          </template>
          <template v-if="column.key == 'hccount'">
            <Tooltip placement="top">
              <template #title>
                <span>核查数量（栋）</span>
              </template>
              <span> 核查数量（栋） </span>
            </Tooltip>
          </template>
          <template v-if="column.key == 'zcl'">
            <Tooltip placement="top">
              <template #title>
                <span>核查率</span>
              </template>
              <span> 核查率 </span>
            </Tooltip>
          </template>
          <template v-if="column.key == 'yhcount'">
            <Tooltip placement="top">
              <template #title>
                <span>隐患数量（个）</span>
              </template>
              <span> 隐患数量（个） </span>
            </Tooltip>
          </template>
          <template v-if="column.key == 'zgcount'">
            <Tooltip placement="top">
              <template #title>
                <span>整改数量（个）</span>
              </template>
              <span> 整改数量（个） </span>
            </Tooltip>
          </template>
        </template>
      </a-table>
      <Detail
        v-model:visible="visible"
        title="抽屉标题"
        :width="1500"
        :detailTableHeight="detailTableHeight"
        :closable="true"
        :destroyOnClose="true"
        :data="detailData"
        :detailParams="detailParams"
        :currentqx="currentqx"
        :currentTitle="currentTitle"
        @close="handleClose"
      >
        <!-- <p>抽屉内容</p> -->
      </Detail>
      <!-- <BasicTable @register="registerTable">
          <template #id="{ record }"> </template>
      </BasicTable> -->

    
    </div>
  </div>
</template>

<script lang="ts" setup>
  import moment from 'moment';
  import dayjs from 'dayjs';
  import { ref, reactive, toRefs, onMounted, onBeforeMount, computed } from 'vue';
  import { getHckProgress, getRegion } from '/@/api/demo/system'; //统计工作进展
  import { useUserStore } from '/@/store/modules/user';
  import { iTableData, iTableColumns } from './types/table';
  import { iParams } from './types/params';
  import { useGlobSetting } from '/@/hooks/setting';
  import { downloadByUrl } from '/@/utils/file/download';
  const userStore = useUserStore();
  const globSetting = useGlobSetting();
  let userInfo = ref<any>(null);
  const visible = ref(false);
  const checkvisible = ref(false);
  let detailData = ref<any[]>([]);
  const role_type = ref<string>('4');
  let options1 = ref<any[]>([]);
  let detailParams = ref({}); // 详情参数
  let detailTableHeight = ref<number>(0); // 表格高度
  let tableHeight = ref<number>(0); // 表格高度
  let pageIndex = ref(1);
  let pageSize = ref(20);
  const dateFormat = 'YYYY-MM-DD';
  const startDate = ref<any>(null); // 开始时间
  const endDate = ref<any>(null); // 结束时间
  const value18 = ref<string[]>([]);
  let data = reactive<{
    tableData: iTableData[];
    tableColumns: iTableColumns[];
    wscolsList: { wch: number }[];
    id: number | any;
    loading: Boolean;
    keyWorld: String;
    currentqx: string; // 当前行政区名称
    currentTitle: string;
    cityToken: string | any;
    startTime: string; // 开始时间
    endTime: string; // 结束时间
  }>({
  // 表格数据
  tableData: [],
  tableColumns: [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      align: 'center',
      width: 130,
    },
    {
      title: '区县名称',
      dataIndex: 'xzq',
      key: 'xzq',
      align: 'center',
      width: 170,
      // customCell: (row, index, column) => {
      //   let isNoHzyh = row.xzq !== '汇总' ? true : false;
      //   let style = 'cursor:pointer;text-decoration: underline; color: blue;';
      //   let isNoZero = row[column.key] !== 0 ? true : false;
      //   return {
      //     style: `${isNoHzyh === true && isNoZero ? style : ''}`,
      //     class: 'cell-hover',
      //     onClick: async () => {
            
      //       getDetailData(row, index, column, isNoHzyh, isNoZero);
      //     },
      //   };
      // },
    },
    {
      title: '房屋总数(栋)',
      dataIndex: 'zcount',
      key: 'zcount',
      align: 'center',
      width: 170,
    },
    {
      title: '核查数量（栋）',
      dataIndex: 'hccount',
      key: 'hccount',
      align: 'center',
      width: 170,
    },
    {
      title: '未核查数量（栋）',
      dataIndex: 'whccount',
      key: 'whccount',
      align: 'center',
      width: 170,
    },
    {
      title: '核查率',
      dataIndex: 'hcl',
      key: 'hcl',
      align: 'center',
      width: 170,
    },
    {
      title: '已达标数量（栋）',
      dataIndex: 'ydbcount',
      key: 'ydbcount',
      align: 'center',
      width: 170,
    },
    {
      title: '未达标数量（栋）',
      dataIndex: 'wdbcount',
      key: 'wdbcount',
      align: 'center',
      width: 170,
    },
    {
      title: '达标率',
      dataIndex: 'dbl',
      key: 'dbl',
      align: 'center',
      width: 130,
    },
    {
      title: '隐患数量（个）',
      dataIndex: 'yhcount',
      key: 'yhcount',
      align: 'center',
      width: 170,
    },
    {
      title: '整改数量（个）',
      dataIndex: 'zgcount',
      key: 'zgcount',
      align: 'center',
      width: 170,
    },
    {
      title: '剩余隐患数量（个）',
      dataIndex: 'syyhcount',
      key: 'syyhcount',
      align: 'center',
        width: 170,
      },
    ],
  id: null,
  loading: true,
    keyWorld: '',
    cityToken: '', // 判断是不是市区 110000 是北京市 展示搜索宽
    currentqx: '', // 当前行政区名称
    currentTitle: '', // 当前详情标题
    wscolsList: [{ wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }],
  });
// 表格的 ref Dom名称
  let { tableData, loading, currentqx, currentTitle } = toRefs(data);
  async function getData() {
  const { role } = userInfo.value;
    if (startDate.value == null) {
    let currentDate = moment().format('YYYY-MM-DD');
    const start: any = dayjs(currentDate);
    const end: any = dayjs(currentDate);
    startDate.value = start;
    endDate.value = end;
    getTime();
  }

  console.log('****************开始时间****************', startDate.value);
  console.log('****************结束时间****************', endDate.value);

  let groupname = '';
  if (role === 'City') {
    groupname = 'qxmc';
  } else if (role === 'Area') {
    groupname = 'jzmc';
  } else if (role === 'Street') {
    groupname = 'czmc';
  }
  let params: iParams = {
    groupname: groupname,
    startTime: moment(startDate.value.$d).format('YYYY-MM-DD'),
    endTime: moment(endDate.value.$d).format('YYYY-MM-DD'),
      roletype: role_type.value,
  };
  if (value18.value != undefined) {
    params.xzqdm = value18.value[0];
    params.towndm = value18.value[1];
    params.villagedm = value18.value[2];
  }
   console.log('@市级参数', params);
  loading.value = true;
  let res: any = await getHckProgress(params);
  console.log('@res--工作进入汇总表', res.items);

  if (res || res.items.length > 0) {
    loading.value = false;
    res.items.forEach((item: any, index: number) => {
      // item.name = selectClassFlyDict(item.xzqdm);
      item.index = index + 1;
      });
      // console.log('data', data);
      // 算列和
      let zcount = total(res.items, 'zcount');
      let hccount = total(res.items, 'hccount');
      let hcl = Math.round(parseFloat((hccount / zcount) * 100)).toFixed(2) + '%';
      let 合计_count = '汇总';
      let yhcount = total(res.items, 'yhcount');
      let zgcount = total(res.items, 'zgcount');

      let wzgcount = total(res.items, 'syyhcount');
	    let yhccount = total(res.items, 'yhccount');
      let whccount = total(res.items, 'whccount');
      let ydbcount = total(res.items, 'ydbcount');
      let wdbcount = total(res.items, 'wdbcount');
      let dbl = Math.round(parseFloat((ydbcount / hccount) * 100)).toFixed(2) + '%';
      let allObj = {
        xzq: 合计_count,
        zcount: zcount,
        hccount: hccount,
        hcl: hcl,
        yhcount: yhcount,
        zgcount: zgcount,
        whccount: whccount,
        syyhcount: wzgcount,
        wdbcount: wdbcount,
        ydbcount: ydbcount,
        dbl: dbl,
	      yhccount: yhccount
    };
    data.tableData = [...res.items, allObj];
  }
}
// 计算总数的方法
function total(arr: any, item: any) {
  let total = arr.reduce((pre: any, cur: any) => {
    return parseInt(pre) + parseInt(cur[item]);
  }, 0);
  return total;
}

const getDetailData = async (
  row: any,
  index: number,
  column: any,
    isNoHzyh: boolean,
    isNoZero: boolean,
) => {
  console.log("****")
      let params = {
        groupbyLever_code: row.xzqdm,
        groupbyLever_code_project: column.key,
        xzq: row.xzq,
        startTime: moment(startDate.value.$d).format('YYYY-MM-DD'),
        endTime: moment(endDate.value.$d).format('YYYY-MM-DD'),
        roletype: role_type.value,
      };
      detailParams.value = params;
      data.currentTitle = row.xzq;
      showDrawer();
};


  // 打开抽屉
  function showDrawer() {
    visible.value = true;
  }
  function handleClose() {
    visible.value = false;
  }
  function handleExport() {
    const uriBase = `${globSetting.apiBaseUrl}${globSetting.apiUrl}`;
    const tk = userStore.getToken;
    let xzqdm = '';
    let towndm = '';
    let villagedmdm = '';
    if (value18.value[0] != undefined) {
      xzqdm = value18.value[0];
    }
    if (value18.value[1] != undefined) {
      towndm = value18.value[1];
    }
    if (value18.value[2] != undefined) {
      villagedmdm = value18.value[2];
    }
    getTime();
    downloadByUrl({
      url:
        uriBase +
        '/hc/evolvestatic/ExportExcel?access_token=' +
        tk +
        '&yhly=' +
        role_type.value +
        '&xzqdm=' +
        xzqdm +
        '&towndm=' +
        towndm +
        '&villagedm=' +
        villagedmdm +
        '&startTime=' +
        startDate.value.format('YYYY-MM-DD') +
        '&endTime=' +
        endDate.value.format('YYYY-MM-DD'),
      target: '_blank',
    });
  }
  function handleMxExport() {
    const uriBase = `${globSetting.apiBaseUrl}${globSetting.apiUrl}`;
    const tk = userStore.getToken;
    let xzqdm = '';
    let towndm = '';
    let villagedm = '';
    if (value18.value[0] != undefined) {
      xzqdm = value18.value[0];
    }
    if (value18.value[1] != undefined) {
      towndm = value18.value[1];
    }
    if (value18.value[2] != undefined) {
      villagedm = value18.value[2];
    }
    getTime();
    downloadByUrl({
      url:
        uriBase +
        '/export/hymx/exporthymx?access_token=' +
        tk +
        '&yhly=' +
        role_type.value +
        '&xzqdm=' +
        xzqdm +
        '&towndm=' +
        towndm +
        '&villagedm=' +
        villagedm +
        '&startTime=' +
        startDate.value.format('YYYY-MM-DD') +
        '&endTime=' +
        endDate.value.format('YYYY-MM-DD'),
      target: '_blank',
    });
  }
function getTime() {
  data.startTime = moment(startDate.value.$d).format('YYYY-MM-DD');
  data.endTime = moment(endDate.value.$d).format('YYYY-MM-DD');
  console.log('@查询参数 -- 开始时间', data.startTime);
  console.log('@查询参数 -- 结束时间', data.endTime);
}
function getUserInfo() {
  const userStore = useUserStore();
  userInfo.value = userStore?.getUserInfo;
}

function searchBtn() {
  getTime();
  data.loading = true;
  getData();
}
async function getRegionData() {
    let res: any = await getRegion();
    options1.value = res;
  }

function onChange(value) {
  value18.value = value;
}
const displayColumns = computed(() => {
  const { role } = userInfo.value;
  let arr: any[] = [];
  if (role === 'City') {
    // qx
    arr = data.tableColumns.filter((item) => item.key !== 'jzmc' && item.key !== 'czmc');
    return arr;
  } else if (role === 'Area') {
    // jz
    arr = data.tableColumns.filter((item) => item.key !== 'czmc' && item.key !== 'qxmc');
    return arr;
  } else if (role === 'Street') {
    // cun
    arr = data.tableColumns.filter((item) => item.key !== 'jzmc' && item.key !== 'qxmc');
    console.log('@Aarr', arr);
    return arr;
  } else {
    return data.tableColumns;
  }
});
const getTableHeight = () => {
  setTimeout(() => {
    detailTableHeight.value = window.innerHeight;
    tableHeight.value = window.innerHeight;
  });
};
onBeforeMount(() => {
  getUserInfo();
});
onMounted(() => {
  console.log('******工作进展统计初始化******');
  getRegionData();
  getData();
  getTableHeight();
  // getTableData();
});
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
#map {
  height: calc(100vh - 140px);
}

.x-houseMng-search {
  z-index: 100;
  margin: 6px;
  position: absolute;
}

.root-house-mng-main {
  margin: 6px;
}

.x-village-tabs {
  //z-index: 100;
  //position: absolute;
  width: 60vw;
  margin-top: 6px;
  margin-left: 40px;
  //background-color: rgba(34, 34, 34, 0.6);
  :deep(.ant-form) {
    margin-top: 6px;
  }

  // :deep(.ant-form-item-label) > label {
  //   color: white;
  // }
}
</style>
